<?php
require_once __DIR__ . '/../config/database.php';

/**
 * 数据库连接类
 */
class Database {
    private $connection;
    private static $instance = null;

    /**
     * 私有构造函数 - 单例模式
     */
    private function __construct() {
        $this->connect();
    }

    /**
     * 获取数据库实例
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 数据库连接
     */
    private function connect() {
        $this->connection = new mysqli(
            DatabaseConfig::DB_HOST,
            DatabaseConfig::DB_USER,
            DatabaseConfig::DB_PASS,
            DatabaseConfig::DB_NAME
        );

        if ($this->connection->connect_error) {
            throw new Exception("数据库连接失败: " . $this->connection->connect_error);
        }

        $this->connection->set_charset(DatabaseConfig::DB_CHARSET);
    }

    /**
     * 执行查询
     */
    public function query($sql, $params = []) {
        $stmt = $this->connection->prepare($sql);
        if (!$stmt) {
            throw new Exception("SQL准备失败: " . $this->connection->error);
        }

        if (!empty($params)) {
            $types = '';
            $bindParams = [];
            
            foreach ($params as $param) {
                if (is_int($param)) {
                    $types .= 'i';
                } elseif (is_float($param)) {
                    $types .= 'd';
                } else {
                    $types .= 's';
                }
                $bindParams[] = $param;
            }
            
            array_unshift($bindParams, $types);
            call_user_func_array([$stmt, 'bind_param'], $this->refValues($bindParams));
        }

        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result) {
            $data = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            return $data;
        } else {
            $affectedRows = $stmt->affected_rows;
            $stmt->close();
            return $affectedRows;
        }
    }

    /**
     * 获取最后插入的ID
     */
    public function getLastInsertId() {
        return $this->connection->insert_id;
    }

    /**
     * 转义字符串
     */
    public function escape($string) {
        return $this->connection->real_escape_string($string);
    }

    /**
     * 引用值用于bind_param
     */
    private function refValues($arr) {
        $refs = [];
        foreach ($arr as $key => $value) {
            $refs[$key] = &$arr[$key];
        }
        return $refs;
    }

    /**
     * 开始事务
     */
    public function beginTransaction() {
        return $this->connection->begin_transaction();
    }

    /**
     * 提交事务
     */
    public function commit() {
        return $this->connection->commit();
    }

    /**
     * 回滚事务
     */
    public function rollback() {
        return $this->connection->rollback();
    }

    /**
     * 关闭连接
     */
    public function close() {
        if ($this->connection) {
            $this->connection->close();
        }
    }
}
